#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <Windows.h>
#include "v2_nim_api.hpp"
#include "v2_nim_def_enum.hpp"
#include "v2_nim_def_struct.hpp"
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(ui->m_btnInitialize, &QPushButton::clicked, this, &MainWindow::onInitializeClicked);
    connect(ui->m_btnRelease, &QPushButton::clicked, this, &MainWindow::onReleaseClicked);

    connect(ui->m_btnLogin, &QPushButton::clicked, this, &MainWindow::onLoginClicked);
    connect(ui->m_btnLogout, &QPushButton::clicked, this, &MainWindow::onLogoutClicked);
    connect(ui->m_btnAddFriend, &QPushButton::clicked, this, &MainWindow::onAddFriendClicked);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::onInitializeClicked()
{
    //auto appkey = ui->m_editAppKey->text();
    auto appkey = "61e681b6306fe6e5cf3c3105b06310e0";
    v2::V2NIMInitOption option;
    option.appkey = appkey;
    v2::V2NIMClient::get().init(option);
    qDebug() << "init";
}

void MainWindow::onAddFriendClicked()
{
    qDebug() << "onAddFriendClick";
    auto& friendService = v2::V2NIMClient::get().getFriendService();
    qDebug() << "friendService";
    v2::V2NIMFriendAddParams params;
    params.addMode = v2::V2NIM_FRIEND_MODE_TYPE_ADD;
    qDebug() << "params addMode";
    params.postscript = "hello";
    friendService.addFriend(
        "94201",
        params,
        []() {

            qDebug() << "Add Friend successfully.";
        }, [](v2::V2NIMError error) {
            qDebug() << "Failed to Add Friend, code: " << error.code << ", message: " << QString::fromStdString(error.desc);
        });
}

void MainWindow::onReleaseClicked()
{
    v2::V2NIMClient::get().uninit();
}

void MainWindow::onLoginClicked()
{
    QNetworkRequest request;
    QNetworkAccessManager* naManager = new QNetworkAccessManager(this);
    QMetaObject::Connection connRet = QObject::connect(naManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onRequestFinished(QNetworkReply*)));
    Q_ASSERT(connRet);
    request.setUrl(QUrl("http://159.75.80.4:23456/api/user/user/pc/login"));
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded;charset=utf-8");
    QUrlQuery postArray;
    postArray.addQueryItem("mobile","17091649768");
    postArray.addQueryItem("areaCode","%2B86");
    postArray.addQueryItem("password","feng6666");
    QByteArray postData = postArray.toString(QUrl::FullyEncoded).toUtf8();
    QNetworkReply* reply = naManager->post(request,postData);
    qDebug() << reply;
    auto& loginService = v2::V2NIMClient::get().getLoginService();
    v2::V2NIMLoginOption option;

    loginService.login(
        "1328906",
        "771ef2066c1c85c1c1c083804b320526",
        //ui->m_editUsername->text().toStdString(),
        //ui->m_editPassword->text().toStdString(),

        option,
        []() {

            qDebug() << "Login successfully.";
        }, [](v2::V2NIMError error) {
            qDebug() << "Failed to login, code: " << error.code << ", message: " << QString::fromStdString(error.desc);
        });

    //accid =1328906 token = 771ef2066c1c85c1c1c083804b320526
}

void MainWindow::onRequestFinished(QNetworkReply* reply){
    // 获取http状态码
    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    if(statusCode.isValid())
        qDebug() << "status code=" << statusCode.toInt();

    QVariant reason = reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();
    if(reason.isValid())
        qDebug() << "reason=" << reason.toString();

    QNetworkReply::NetworkError err = reply->error();
    if(err != QNetworkReply::NoError) {
        qDebug() << "Failed: " << reply->errorString();
    }
    else {
        // 获取返回内容
        qDebug() << "feedback response body";
        qDebug() << reply->readAll();
        qDebug() << "reponse end";
    }
}

void MainWindow::onLogoutClicked()
{
    auto& loginService = v2::V2NIMClient::get().getLoginService();
    loginService.logout([]() {
        qDebug() << "Logout successfully.";
    }, [](v2::V2NIMError error) {
        qDebug() << "Failed to logout, code: " << error.code << ", message: " << QString::fromStdString(error.desc);
    });
}


void MainWindow::on_pushButton_clicked()
{
    qDebug() << "search friend";
    auto& friendService = v2::V2NIMClient::get().getFriendService();
    qDebug() << "search FriendService triggered";
    v2::V2NIMFriendSearchOption option;
    option.keyword = "94201";
    qDebug() << "search parameter";
    friendService.searchFriendByOption(
        option,
        [](nstd::vector<v2::V2NIMFriend> friends) {
            // search friend success, handle friends
            qDebug() << "search friend success";
        },
        [](v2::V2NIMError error) {
            // search friend failed, handle error
            qDebug() << "Failed to searchfriend, code: " << error.code << ", message: " << QString::fromStdString(error.desc);
        });
}

